//
//  GLTabBar.m
//  GLTabBar
//
//  Created by 张国梁 on 15/11/2.
//  Copyright © 2015年 CoderGL. All rights reserved.
//

#import "GLTabBar.h"

@interface GLTabBar ()
@property (nonatomic, weak) UIButton *customButton;
@end

@implementation GLTabBar
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        // 添加中间自定义不规则按钮
        [self setupCustomButton];
        
    }
    return self;
}

#pragma mark - 添加中间自定义不规则按钮
- (void)setupCustomButton {
    
    UIButton *customButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [customButton setBackgroundImage:[UIImage imageNamed:@"post_normal"] forState:UIControlStateNormal];
    [customButton setBackgroundImage:[UIImage imageNamed:@"post_normal"] forState:UIControlStateHighlighted];
    [customButton addTarget:self action:@selector(customButtonClick) forControlEvents:UIControlEventTouchDown];
    self.customButton = customButton;
    [self addSubview:customButton];
}

- (void)customButtonClick {
    if ([self.tabBarDelegate respondsToSelector:@selector(tabBarDidClickCustomButton:)]) {
        [self.tabBarDelegate tabBarDidClickCustomButton:self];
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    // 设置自定义按钮的frame
    [self setupCustomButtonFrame];
    
    // 设置所有的tabBar按钮的frame
    [self setupAllTabBarButtonsFrame];
}

/**
 *  设置自定义按钮的frame
 */
- (void)setupCustomButtonFrame {
    [self.customButton sizeToFit];
    self.customButton.center = CGPointMake(self.bounds.size.width * 0.5, self.bounds.size.height * 0.5 - 10);
}

/**
 *  设置所有的tabBar按钮的frame
 */
- (void)setupAllTabBarButtonsFrame {
    // 记录索引
    NSInteger index = 0;
    
    // 循环遍历子控件找出按钮并设置尺寸
    for (UIView *tabBarButton in self.subviews) {
        // 删除那根黑线
        if (tabBarButton.bounds.size.height == 0.5) {
            [tabBarButton removeFromSuperview];
        }
        if (![tabBarButton isKindOfClass:NSClassFromString(@"UITabBarButton")]) continue;
        [self setupTabBarButtonFrame:tabBarButton index:index];
        index ++;
    }
    
}

/**
 *  设置tabBarButton按钮的尺寸
 *
 *  @param index        索引
 */
- (void)setupTabBarButtonFrame:(UIView *)tabBarButton index:(NSInteger)index {
    
    self.itemWidth = self.bounds.size.width / (self.items.count + 1);
    
    CGRect frame = tabBarButton.frame;
    frame.origin.y = 0;
    frame.size.height = self.bounds.size.height;
    frame.size.width = self.itemWidth;
    frame.origin.x = self.itemWidth * index;
    tabBarButton.frame = frame;
    
    if (index >= 2) {
        frame.origin.x = self.itemWidth * (index + 1);
        tabBarButton.frame = frame;
    }
}
@end
